import { getApiUrl, getWebrtcUrl, getIceServers, isDev } from '../config';

// 存储当前的WebRTC连接状态
let pc = null;
let localStream = null;
let sessionid = null;

// 添加状态回调支持
let statusCallback = null;

/**
 * 连接到SRS WebRTC服务器并开始推流
 * @param {MediaStream} stream - 媒体流对象
 * @returns {Promise<Object>} - 返回包含推流URL和会话ID的对象
 */
export const connectWebRTC = async (stream) => {
  if (!stream) {
    throw new Error('没有提供媒体流');
  }
  
  try {
    // 保存流的引用
    localStream = stream;
    
    // 获取API URL
    const apiUrl = getApiUrl('/v1/publish/');
    console.log('连接到SRS WebRTC API:', apiUrl);
    
    // 创建新的PeerConnection
    // 如果已经存在PeerConnection，先关闭它
    if (pc) {
      console.log('关闭已存在的PeerConnection');
      await stopWebRTC();
    }
    
    // 创建新的PeerConnection，使用更健壮的配置
    pc = new RTCPeerConnection({
      iceServers: getIceServers(),
      // 添加更多配置以提高连接成功率
      iceTransportPolicy: 'all',
      iceCandidatePoolSize: 10,
      bundlePolicy: 'max-bundle',
      rtcpMuxPolicy: 'require'
    });
    
    // 添加所有音视频轨道到PeerConnection
    stream.getTracks().forEach(track => {
      pc.addTrack(track, stream);
      console.log('添加轨道到PeerConnection:', track.kind);
    });
    
    // 添加超时检查
    let iceConnectionTimeout = setTimeout(() => {
      if (pc && (pc.iceConnectionState === 'checking' || pc.iceConnectionState === 'new')) {
        console.error('ICE连接超时');
        if (statusCallback) {
          statusCallback({
            status: 'ice',
            state: 'failed',
            reason: 'timeout'
          });
        }
      }
    }, 30000);  // 30秒超时
    
    pc.oniceconnectionstatechange = (e) => {
      console.log('ICE连接状态:', pc.iceConnectionState);
      
      // 通知状态变化
      if (statusCallback) {
        statusCallback({
          status: 'ice', 
          state: pc.iceConnectionState
        });
      }
      
      // 清除超时定时器
      if (pc.iceConnectionState !== 'checking' && pc.iceConnectionState !== 'new') {
        clearTimeout(iceConnectionTimeout);
      }
      
      // 连接失败处理
      if (pc.iceConnectionState === 'failed' || pc.iceConnectionState === 'disconnected') {
        console.error('ICE连接失败，状态:', pc.iceConnectionState);
        // 此处不要关闭连接，让外部处理重连
      }
    };
    
    pc.onicegatheringstatechange = () => {
      console.log('ICE收集状态:', pc.iceGatheringState);
      if (pc.iceGatheringState === 'complete') {
        console.log('ICE候选收集完成，所有候选数量：', pc.localDescription.sdp.match(/a=candidate/g)?.length || 0);
      }
    };
    
    pc.onicecandidate = (e) => {
      if (e.candidate) {
        console.log('收集到ICE候选:', {
          type: e.candidate.type,
          protocol: e.candidate.protocol,
          address: e.candidate.address,
          port: e.candidate.port
        });
      } else {
        console.log('ICE候选收集完成');
      }
    };
    
    pc.onconnectionstatechange = () => {
      console.log('PeerConnection状态变化:', pc.connectionState);
    };
    
    pc.onsignalingstatechange = () => {
      console.log('信令状态变化:', pc.signalingState);
    };
    
    // 创建SDP offer
    const offer = await pc.createOffer();
    await pc.setLocalDescription(offer);
    
    // 等待ICE候选收集完成
    const offerSDP = pc.localDescription;
    
    console.log('发送Offer到SRS服务器:', offerSDP.sdp);
    
    // 添加更多调试信息
    console.log('WebRTC配置信息:', {
      apiUrl,
      iceServers: pc.getConfiguration().iceServers,
      streamUrl: getWebrtcUrl()
    });
    
    try {
      // 发送Offer到SRS服务器
      const response = await fetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          api: 'publish',
          streamurl: getWebrtcUrl(),
          sdp: offerSDP.sdp
        }),
        // 确保包含凭证，支持HTTPS环境下的cookie
        credentials: 'include'
      });
      
      if (!response.ok) {
        console.error('SRS服务器响应错误:', {
          status: response.status,
          statusText: response.statusText,
          headers: Object.fromEntries(response.headers.entries())
        });
        throw new Error(`SRS服务器响应错误: ${response.status} ${response.statusText}`);
      }
      
      const data = await response.json();
      console.log('收到SRS响应:', data);
      
      if (data.code !== 0) {
        console.error('SRS错误详情:', {
          code: data.code,
          data: data.data || '未提供详细信息',
          fullResponse: JSON.stringify(data)
        });
        throw new Error(`SRS错误: ${data.code}, ${data.data || '服务器未返回详细信息'}`);
      }
      
      // 设置远程描述
      const answer = new RTCSessionDescription({
        type: 'answer',
        sdp: data.sdp
      });
      
      await pc.setRemoteDescription(answer);
      console.log('已设置远程描述');
      
      // 保存会话ID
      sessionid = data.sessionid;
      
      return {
        publishUrl: getWebrtcUrl(),
        sessionid: sessionid
      };
    } catch (error) {
      console.error('API请求失败:', error);
      throw error;
    }
  } catch (error) {
    console.error('WebRTC连接失败:', error);
    throw error;
  }
};

/**
 * 停止WebRTC连接并释放资源
 */
export const stopWebRTC = async () => {
  console.log('停止WebRTC连接...');
  try {
    // 关闭PeerConnection
    if (pc) {
      // 先将所有轨道设为disabled
      pc.getSenders().forEach(sender => {
        if (sender.track) {
          sender.track.enabled = false;
        }
      });
      
      // 关闭连接
      pc.close();
      console.log('PeerConnection已关闭');
    }
    
    // 重置所有变量
    pc = null;
    localStream = null;
    sessionid = null;
    
    // 通知状态变化
    if (typeof statusCallback === 'function') {
      statusCallback({
        status: 'closed',
        state: 'closed'
      });
    }
    
    return true;
  } catch (error) {
    console.error('关闭WebRTC连接出错:', error);
    // 即使出错也重置连接
    pc = null;
    localStream = null;
    sessionid = null;
    return false;
  }
};

/**
 * 检查WebRTC连接状态
 * @returns {Object} - 连接状态信息
 */
export const getWebRTCStatus = (callback) => {
  statusCallback = callback;
};

/**
 * 重新连接WebRTC
 * @returns {Promise<Object>} - 返回包含推流URL和会话ID的对象
 */
export const reconnectWebRTC = async () => {
  // 如果存在本地流，使用它重新连接
  if (localStream) {
    return await connectWebRTC(localStream);
  } else {
    throw new Error('没有可用的媒体流进行重连');
  }
};

// 设置状态回调
export const setStatusCallback = (callback) => {
  statusCallback = callback;
}; 